package com.yiwenup.exception.config;

import cn.hutool.core.util.StrUtil;
import com.yiwenup.common.constant.BaseConstant;
import com.yiwenup.common.constant.SystemConstant;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.util.Locale;
import java.util.Properties;

/**
 * 国际化配置
 **/
@ConfigurationProperties(prefix = "yiwenup.i18n", ignoreInvalidFields = true)
@Configuration
public class I18nConfig implements InitializingBean {

    /**
     * 国际化
     */
    @Setter
    private Locale locale = new Locale(BaseConstant.DEFAULT);

    /**
     * 国际化文件抽象
     */
    private static Properties properties;

    @Override
    public void afterPropertiesSet() throws Exception {
        properties = PropertiesLoaderUtils.loadAllProperties(
                StrUtil.format(SystemConstant.I18N_PROP_LOCATION,
                        this.locale));
    }

    /**
     * 格式化信息，若没有对应的国际化信息或者业务参数为空，都将返回错误码作为错误信息
     *
     * @return 格式化信息
     */
    public static String formatMsg(String key, Object... args) {
        // 获取配置的 message
        String msg = properties.getProperty(key);
        if (msg == null || args == null || args.length == 0) return key;
        // 执行格式化
        return StrUtil.format(msg, args);
    }
}
